package uit.nfcmenu.models;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseAdapter {

	/** The m db helper. */
	protected static DatabaseHelper mDbHelper;

	/** The m db. */
	protected SQLiteDatabase mDb;

	/** The m ctx. */
	protected final Context mCtx;

	/**
	 * Open.
	 * 
	 * @return the database adapter
	 */
	public DatabaseAdapter open() {
		mDbHelper = new DatabaseHelper(mCtx);

		try {

			if (mDb != null && mDb.isOpen())
				mDb.close();
			mDb = mDbHelper.getWritableDatabase();
		} catch (Exception e) {
			if (mDb != null && mDb.isOpen())
				mDb.close();
			mDb = mDbHelper.getReadableDatabase();
		}

		return this;
	}

	// close db
	/**
	 * Close.
	 */
	public void close() {
		mDb.close();
	}

	/**
	 * Table exist.
	 * 
	 * @param table
	 *            the table
	 * @return true, if successful
	 */
	public boolean tableExist(String table) {
		Cursor cursor = mDb.rawQuery("SELECT * FROM " + table, null);
		if (cursor != null && cursor.getCount() > 0) {
			cursor.close();
			return true;
		}
		cursor.close();
		return false;
	}

	/**
	 * Number row in database.
	 * 
	 * @param table
	 *            the table
	 * @return the int
	 */
	public int numberRowInDatabase(String table) {
		int count = 0;
		this.open();
		Cursor cursor = null;
		try {
			cursor = mDb.rawQuery("SELECT * FROM " + table, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.close();
				count = cursor.getCount();
			}
		} finally {
			if (cursor != null)
				cursor.close();
			this.close();
		}

		return count;
	}

	/**
	 * Instantiates a new database adapter.
	 * 
	 * @param context
	 *            the context
	 */
	public DatabaseAdapter(Context context) {
		mCtx = context;
	}
}
